<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:protype:remove']"
        >删除</el-button>
      </el-col>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" style="float:right;">刷新</el-button>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="templatePreview(scope.row)"
          >下载预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改产品类别管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" height="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入类别名称"  :readonly="temlateNamRead" style="width:400px;"/><span style="color:red;"> 模板名称后缀必须为.ftl；参数替换参考${map.xxx}</span>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" :rows="28"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConTemplates, editTemplateInit, editTemplate, deleteTemplate, templatePreview } from "@/api/crm/templates/bid/templates";

export default {
  name: "Protype",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      templateNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板列表数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      temlateNamRead: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询模板列表 */
    getList() {
      this.loading = true;
      listConTemplates().then(response => {
        this.templateList = response;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.templateNames = selection.map(item => item.templateName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.temlateNamRead = false;
      this.title = "添加模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateName = row.templateName || this.templateNames[0]
      editTemplateInit(templateName).then(response => {
        this.form = response;
        this.open = true;
        this.temlateNamRead = true;
        this.title = "修改模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          //获取最后一个.的位置
          var index= this.form.templateName.lastIndexOf(".");
          //获取后缀
          var ext = this.form.templateName.substr(index+1);
          if("ftl" == ext){
            editTemplate(this.form).then(response => {
              if(response.result){
                this.msgSuccess("保存成功");
                this.open = false;
                this.getList();
              }else{
                this.msgError("保存失败");
                this.open = false;
                this.getList();
              }
              
            });
          }else{
            this.msgError("模板名称后缀必须为.ftl");
          }
          
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if(null != row){
        this.templateNames.push(row.templateName)
      }
      const templateName = this.templateNames;
      this.$confirm('确认删除该模板?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return deleteTemplate(templateName);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    // 表单重置
    reset() {
      this.form = {
        templateName: null,
        content: null
      };
      this.resetForm("form");
    },
    //模板下载预览
    templatePreview(item){
      templatePreview(item.templateName).then(response => {
          let blob = new Blob([response], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          }); // res就是接口返回的文件流了
          let url = window.URL || window.webkitURL;
          let fileURL = url.createObjectURL(blob);
          let a = document.createElement("a");
          a.href = fileURL;
          a.download = item.templateName + ".doc";
          a.target = "_self";
          a.click();
          url.revokeObjectURL(fileURL);
        });
    }
  }
};
</script>